package cn.hamster3.mc.plugin.core.bungee;

import cn.hamster3.mc.plugin.core.bungee.api.CoreBungeeAPI;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.common.config.YamlConfig;
import cn.hamster3.mc.plugin.core.common.util.UpdateCheckUtils;
import lombok.Getter;
import net.kyori.adventure.platform.bungeecord.BungeeAudiences;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Plugin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;

@SuppressWarnings("CallToPrintStackTrace")
public class HamsterCorePlugin extends Plugin {
    @Getter
    private static HamsterCorePlugin instance;
    @Getter
    private BungeeAudiences audienceProvider;

    @Override
    public void onLoad() {
        instance = this;
        long start = System.currentTimeMillis();
        Logger logger = getLogger();
        logger.info("仓鼠核心正在初始化");
        try {
            File dataFolder = getDataFolder();
            if (dataFolder.mkdir()) {
                logger.info("已生成插件存档文件夹");
            }
            File configFile = new File(dataFolder, "config.yml");
            if (!configFile.exists()) {
                try (InputStream stream = getResourceAsStream("config.yml")) {
                    if (stream != null) {
                        Files.copy(stream, configFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            }
            CoreBungeeAPI.init(configFile);
            logger.info("已初始化 CoreAPI");
        } catch (Exception e) {
            logger.warning("初始化 CoreAPI 出错");
            e.printStackTrace();
        }
        long time = System.currentTimeMillis() - start;
        logger.info("仓鼠核心初始化完成，总计耗时 " + time + " ms");
    }

    @Override
    public void onEnable() {
        long start = System.currentTimeMillis();
        Logger logger = getLogger();
        logger.info("仓鼠核心正在启动");
        audienceProvider = BungeeAudiences.create(this);
        logger.info("已创建 AudienceProvider");
        long time = System.currentTimeMillis() - start;
        logger.info("仓鼠核心启动完成，总计耗时 " + time + " ms");

        CoreAPI.getInstance().getExecutorService().submit(() -> {
            for (Plugin plugin : ProxyServer.getInstance().getPluginManager().getPlugins()) {
                try (InputStream stream = plugin.getResourceAsStream("update.yml")) {
                    if (stream == null) {
                        continue;
                    }
                    try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                        YamlConfig config = YamlConfig.load(reader);
                        UpdateCheckUtils.showUpdate(
                                plugin.getDescription().getName(), config,
                                (s) -> ProxyServer.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(s))
                        );
                    }
                } catch (IOException ignored) {
                }
            }
        });
    }

    @Override
    public void onDisable() {
        long start = System.currentTimeMillis();
        Logger logger = getLogger();
        CoreAPI.getInstance().getJedisPool().close();
        logger.info("已关闭 Redis 连接池");
        CoreAPI.getInstance().getHikariDataSource().close();
        logger.info("已关闭数据库连接池");
        CoreAPI.getInstance().getExecutorService().shutdownNow();
        logger.info("已关闭 ExecutorService 线程池");
        CoreAPI.getInstance().getScheduledService().shutdownNow();
        logger.info("已关闭 ScheduledExecutorService 线程池");
        long time = System.currentTimeMillis() - start;
        logger.info("仓鼠核心已关闭，总计耗时 " + time + " ms");
    }
}
